<script lang="tsx">
import { defineComponent, ref, computed, onMounted } from 'vue';
import { ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElMessage, ElMessageBox, ElCascader } from 'element-plus';
import { useRoute } from 'vue-router';
import { $t } from '@vben/locales';
import { provinceCityOptions } from '@vben/utils';
import { teamNatureOptions } from './const';
import { getGroupListApi, createTeamInfoApi, updateTeamInfoApi, deleteTeamInfoApi, getTeamInfoAndMembersListApi, type Group, type CreateTeamInfo, type UpdateTeamInfo, type TeamFullInfo } from '#/api/competition/registration-info';
import TeamList from './modules/contests/team-list.vue';
import CollapsibleTeamPanel from './modules/contests/collapsible-team-panel.vue';
import SubmissionForm from './modules/contests/submission-form.vue';
import UploadWorks from './modules/contests/upload-works.vue';
import type { TeamInfo } from './modules/contests/team-list.vue';
import { VbenIcon } from '@vben-core/shadcn-ui';
import { UserRoundPlus, UserRoundCog, FileUser, FolderUp } from '@vben/icons';

export default defineComponent({
  name: 'CompetitionHomeContests',
  components: {
    TeamList,
    CollapsibleTeamPanel,
    SubmissionForm,
    UploadWorks
  },
  setup() {
    // 获取路由实例
    const route = useRoute();

    // 当前步骤，0表示第一步
    const activeStep = ref(0);

    // 弹窗显示状态
    const dialogVisible = ref(false);
    const isEditMode = ref(false);
    const currentEditTeam = ref<TeamInfo | null>(null);

    // 编辑报名数据
    const editRegistrationData = ref<any>(null);

    // 组别选项数据
    const groupOptions = ref<Group[]>([]);
    const groupLoading = ref(false);

    // 团队列表数据
    const teamList = ref<TeamInfo[]>([]);

    // 保存完整的团队数据（包括成员信息）
    const fullTeamData = ref<TeamFullInfo[]>([]);

    // 表单数据 - 对应API字段结构
    const formData = ref({
      id: '', // 团队ID
      groupId: '', // 组别ID
      compId: '', // 大赛ID
      name: '', // 团队名称
      type: '', // 团队类型（团队性质）
      organName: '', // 单位名称
      city: '', // 城市
      province: '', // 省份
      img: '', // 图片URL或文件名
      provinceCitySelection: [] as string[] // 级联选择器的值 [provinceCode, cityCode]
    });

    // 表单验证规则
    const formRules = {
      name: [
        { required: true, message: $t('contests.createTeamDialog.required'), trigger: 'blur' },
        { max: 20, message: $t('contests.createTeamDialog.maxLength', { max: 20 }), trigger: 'blur' }
      ],
      groupId: [
        { required: true, message: $t('contests.createTeamDialog.required'), trigger: 'change' }
      ],
      type: [
        { required: true, message: $t('contests.createTeamDialog.required'), trigger: 'change' }
      ],
      provinceCitySelection: [
        {
          required: true,
          validator: (_rule: any, value: string[], callback: Function) => {
            if (!value || value.length < 2) {
              callback(new Error($t('contests.createTeamDialog.required')));
            } else {
              callback();
            }
          },
          trigger: 'change'
        }
      ],
      organName: [
        { required: true, message: $t('contests.createTeamDialog.required'), trigger: 'blur' }
      ]
    };

    // 解析拼接的省市字符串
    // 示例：
    // "北京市东城区" → { province: "北京市", city: "东城区" }
    // "河北省石家庄市" → { province: "河北省", city: "石家庄市" }
    // "河北省" → { province: "河北省", city: "" }
    const parseProvinceCity = (provinceCityStr: string) => {
      let province = '';
      let city = '';

      if (!provinceCityStr) {
        return { province, city };
      }

      // 遍历省份数据，找到匹配的省份和城市
      for (const provinceOption of provinceCityOptions) {
        const provinceName = provinceOption.label;

        // 检查字符串是否以当前省份名开头
        if (provinceCityStr.startsWith(provinceName)) {
          province = provinceName;

          // 提取省份名之后的部分作为城市名
          const remainingStr = provinceCityStr.slice(provinceName.length);

          if (remainingStr) {
            // 在当前省份的城市列表中查找匹配的城市
            const cityOption = provinceOption.children.find(city =>
              remainingStr === city.label || remainingStr.startsWith(city.label)
            );

            if (cityOption) {
              city = cityOption.label;
            } else {
              // 如果没有找到精确匹配的城市，直接使用剩余字符串
              city = remainingStr;
            }
          }
          break;
        }
      }

      // 如果没有找到匹配的省份，尝试从末尾匹配（可能是"市"结尾的直辖市等情况）
      if (!province) {
        for (const provinceOption of provinceCityOptions) {
          const provinceName = provinceOption.label;
          if (provinceCityStr.endsWith(provinceName) || provinceCityStr === provinceName.slice(0, -1)) {
            province = provinceName;
            city = '';
            break;
          }
        }
      }

      // 如果仍然没有找到，可能是特殊格式，直接返回原字符串作为省份
      if (!province && provinceCityStr) {
        province = provinceCityStr;
      }

      return { province, city };
    };

    // 步骤配置
    const steps = computed(() => [
      {
        title: $t('contests.steps.createTeam'),
        isActive: activeStep.value >= 0,
        isCompleted: activeStep.value > 0,
        icon: UserRoundPlus
      },
      {
        title: $t('contests.steps.manageMembers'),
        isActive: activeStep.value >= 1,
        isCompleted: activeStep.value > 1,
        icon: UserRoundCog
      },
      {
        title: $t('contests.steps.submitWork'),
        isActive: activeStep.value >= 2,
        isCompleted: activeStep.value > 2,
        icon: FileUser
      },
      {
        title: $t('contests.steps.uploadWorks'),
        isActive: activeStep.value >= 3,
        isCompleted: activeStep.value > 3,
        icon: FolderUp
      }
    ]);



    // 打开新增团队弹窗
    const openCreateTeamDialog = () => {
      isEditMode.value = false;
      currentEditTeam.value = null;
      dialogVisible.value = true;
      // 重置表单
      formData.value = {
        id: '',
        groupId: '',
        compId: '',
        name: '',
        type: '',
        organName: '',
        city: '',
        province: '',
        img: '',
        provinceCitySelection: []
      };
    };

    // 根据省市名称查找对应的代码
    const findProvinceCityByName = (provinceName: string, cityName: string): any[] => {
      try {
        const province = provinceCityOptions.find(p => p.label === provinceName);
        const city = province?.children?.find(c => c.label === cityName);
        return [province?.value || '', city?.value || ''];
      } catch (error) {
        return [];
      };
    }

    // 编辑团队
    const handleEditTeam = (team: TeamInfo) => {
      isEditMode.value = true;
      currentEditTeam.value = team;
      dialogVisible.value = true;

      // 分解省市信息
      let province = team.province || '';
      let city = team.city || '';

      // 如果有location字段（provinceCity的显示格式），尝试从中分解省市
      if (team.location && team.location.includes('/')) {
        const parts = team.location.split('/');
        province = parts[0]?.trim() || province;
        city = parts[1]?.trim() || city;
      }
      // 查找对应的省市代码
      const provinceCitySelection = findProvinceCityByName(province, city);

      console.log(`找到的省市代码:`, provinceCitySelection);

      // 填充表单 - 优先使用API字段
      formData.value = {
        id: team.id || '',
        groupId: team.groupId || team.participantGroup || '',
        compId: team.compId || '',
        name: team.name,
        type: team.type || '',
        organName: team.organName || team.organization || '',
        city: city,
        province: province,
        img: team.img || '',
        provinceCitySelection: provinceCitySelection
      };
    };

    // 删除团队
    const handleDeleteTeam = async (team: TeamInfo) => {
      try {
        await ElMessageBox.confirm(
          $t('contests.teamList.confirmDelete'),
          $t('contests.teamList.delete'),
          {
            confirmButtonText: $t('contests.createTeamDialog.confirm'),
            cancelButtonText: $t('contests.createTeamDialog.cancel'),
            type: 'warning',
          }
        );

        // 调用删除团队API
        await deleteTeamInfoApi(team.id);

        // 刷新团队列表以获取最新数据
        await fetchTeamList();
        ElMessage.success($t('contests.teamList.deleteSuccess'));
      } catch (error) {
        // 用户取消删除或API调用失败（axios已有错误拦截提示）
      }
    };

    // 关闭弹窗
    const closeDialog = () => {
      dialogVisible.value = false;
      isEditMode.value = false;
      currentEditTeam.value = null;
    };

    // 提交表单
    const handleSubmit = async () => {
      try {
        // 从级联选择器中提取省市信息
        if (formData.value.provinceCitySelection.length >= 2) {
          const provinceCode = formData.value.provinceCitySelection[0];
          const cityCode = formData.value.provinceCitySelection[1];

          // 获取省市显示文本
          const province = provinceCityOptions.find(p => p.value === provinceCode);
          const city = province?.children?.find(c => c.value === cityCode);

          // 更新province和city字段为显示文本
          formData.value.province = province?.label || '';
          formData.value.city = city?.label || '';
        }

        if (isEditMode.value && currentEditTeam.value) {
          // 编辑模式：更新现有团队
          const updateTeamData: UpdateTeamInfo = {
            id: currentEditTeam.value.id,
            groupId: formData.value.groupId,
            compId: formData.value.compId || currentEditTeam.value.compId,
            name: formData.value.name,
            type: formData.value.type,
            organName: formData.value.organName,
            city: formData.value.city,
            province: formData.value.province,
            img: formData.value.img || currentEditTeam.value.img || ''
          };

          // 调用更新团队API
          await updateTeamInfoApi(updateTeamData);

          // 刷新团队列表以获取最新数据
          await fetchTeamList();
          ElMessage.success('更新成功！');
        } else {
          // 新增模式：创建新团队
          // 获取matchId作为compId
          const matchId = route.query.matchId as string;

          if (!matchId) {
            ElMessage.error('缺少大赛ID参数');
            return;
          }

          // 准备API请求数据
          const createTeamData: CreateTeamInfo = {
            groupId: formData.value.groupId,
            compId: matchId,
            name: formData.value.name,
            type: formData.value.type,
            organName: formData.value.organName,
            city: formData.value.city,
            province: formData.value.province,
            img: formData.value.img
          };

          // 调用创建团队API
          await createTeamInfoApi(createTeamData);

          // 刷新团队列表以获取最新数据
          await fetchTeamList();
          ElMessage.success($t('contests.createTeamDialog.createSuccess'));

          // 推进步骤（仅新增时）
          if (activeStep.value < 3) {
            activeStep.value++;
          }
        }

        closeDialog();
      } catch (error) {
        ElMessage.error(isEditMode.value ? '更新失败，请重试' : '创建失败，请重试');
      }
    };

    // 获取组别选项数据
    const fetchGroupOptions = async () => {
      try {
        groupLoading.value = true;
        // 从路由query参数中获取matchId作为compId
        const matchId = route.query.matchId as string;

        if (!matchId) {
          ElMessage.error('缺少大赛ID参数');
          return;
        }

        const { data } = await getGroupListApi({
          compId: matchId,
          curPage: 1,
          pageSize: 100 // 获取所有组别
        });

        groupOptions.value = data || [];
      } catch (error) {
        console.error('获取组别数据失败:', error);
        ElMessage.error('获取组别数据失败，请重试');
        groupOptions.value = [];
      } finally {
        groupLoading.value = false;
      }
    };

    // 获取团队列表数据
    const fetchTeamList = async () => {
      try {
        // 从路由query参数中获取matchId作为compId
        const matchId = route.query.matchId as string;

        if (!matchId) {
          ElMessage.error('缺少大赛ID参数');
          return;
        }

        const { data } = await getTeamInfoAndMembersListApi({
          compId: matchId,
          curPage: 1,
          pageSize: 100
        });

        // 保存完整的团队数据
        fullTeamData.value = data;

        // 转换API数据为前端TeamInfo格式
        teamList.value = data.map((teamData: TeamFullInfo) => {
          // 获取团队性质显示文本
          const natureOption = teamNatureOptions.find(opt => opt.value === teamData.type);

          // 分解省市信息
          let province = '';
          let city = '';

          if (teamData.provinceCity) {
            // 解析拼接的省市字符串
            const result = parseProvinceCity(teamData.provinceCity);
            province = result.province;
            city = result.city;
          }

          // 如果API直接返回了province和city字段，优先使用
          if (teamData.province) province = teamData.province;
          if (teamData.city) city = teamData.city;

          const teamInfo: TeamInfo = {
            // API字段
            id: teamData.id,
            name: teamData.name,
            type: teamData.type,
            organName: teamData.organName,
            city: city,
            province: province,
            groupId: teamData.groupId,
            compId: teamData.compId,
            img: teamData.img,
            memberCount: teamData.memberCount,

            // 兼容性字段
            nature: natureOption?.label || teamData.type,
            location: teamData.provinceCity,
            organization: teamData.organName,
            participantGroup: teamData.groupId
          };
          return teamInfo;
        });
      } catch (error) {
        console.error('获取团队列表失败:', error);
      }
    };



    // 切换到指定步骤
    const switchToStep = (stepIndex: number) => {
      // 只有在有团队的情况下才能进入管理团队步骤
      if (stepIndex === 1 && teamList.value.length === 0) {
        ElMessage.warning('请先创建团队');
        return;
      }
      // 只有在有团队的情况下才能进入提交报名步骤
      if (stepIndex === 2 && teamList.value.length === 0) {
        ElMessage.warning('请先创建团队');
        return;
      }
      // 只有在有团队的情况下才能进入上传作品步骤
      if (stepIndex === 3 && teamList.value.length === 0) {
        ElMessage.warning('请先创建团队');
        return;
      }
      activeStep.value = stepIndex;
    };

    // 编辑报名信息 - 从上传作品页面回到提交报名步骤
    const handleEditRegistration = (registrationData: any) => {
      console.log('编辑报名信息:', registrationData);
      editRegistrationData.value = registrationData;
      activeStep.value = 2; // 回到提交报名步骤
    };

    // 重新提交报名 - 从上传作品页面回到提交报名步骤
    const handleResubmitRegistration = (registrationData: any) => {
      console.log('重新提交报名:', registrationData);
      editRegistrationData.value = registrationData;
      activeStep.value = 2; // 回到提交报名步骤
    };

    // 渲染步骤条
    const renderSteps = () => (
      <div class="w-[1200px] h-[88px] bg-white flex items-center justify-center mt-[16px] mb-[24px] rounded-lg">
        <div class="flex items-center justify-between w-full max-w-4xl px-12">
          {steps.value.map((step, index) => (
            <div
              key={index}
              class="flex items-center relative cursor-pointer"
              onClick={() => switchToStep(index)}
            >
              {/* 步骤圆圈 */}
              <div class={[
                'w-12 h-12 rounded-full flex items-center justify-center font-semibold text-lg mb-2 relative z-10',
                step.isActive ? 'bg-blue-500' : 'bg-gray-200 text-gray-400 hover:bg-gray-300'
              ]}>
                <VbenIcon icon={step.icon} class="text-white" />
              </div>
              {/* 步骤标题 */}
              <span class={[
                'text-sm font-medium transition-colors ml-[8px]',
                step.isActive ? 'text-blue-500' : 'text-gray-400 hover:text-gray-600'
              ]}>
                {step.title}
              </span>
              {/* 连接线到下一步 (最后一步不显示) */}
              {index < steps.value.length - 1 && (
                <div class="absolute left-[120px]">
                  {/* 线条 */}
                  <div class={[
                    'absolute top-0 left-0 w-[90px] border-t-2 border-dashed',
                    step.isCompleted ? 'border-blue-500' : 'border-gray-200'
                  ]}></div>
                  {/* 箭头（小三角） */}
                  <div class={[
                    'absolute top-[-5px] left-[90px] w-0 h-0 border-y-[6px] border-y-transparent border-l-[10px]',
                    step.isCompleted ? 'border-l-blue-500' : 'border-l-gray-200'
                  ]}></div>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    );

    // 渲染团队列表
    const renderTeamList = () => (
      <TeamList
        teamList={teamList.value}
        onAdd-team={openCreateTeamDialog}
        onEdit-team={handleEditTeam}
        onDelete-team={handleDeleteTeam}
      />
    );

    // 渲染团队管理面板
    const renderTeamManagement = () => (
      <div class="w-[1200px] min-h-[616px]">
        {/* 可折叠团队面板列表 */}
        {teamList.value.length > 0 ? (
          <div class="space-y-4">
            {teamList.value.map((team, index) => (
              <CollapsibleTeamPanel
                key={team.id}
                team={team}
                isFirstTeam={index === 0}
                onEdit-team={handleEditTeam}
                onDelete-team={handleDeleteTeam}
              />
            ))}
          </div>
        ) : (
          <div class="text-center py-16">
            <div class="text-gray-400 text-6xl mb-4">📝</div>
            <h3 class="text-lg font-medium text-gray-900 mb-2">暂无团队</h3>
            <p class="text-gray-600">请先创建团队，然后再进行管理</p>
            <button
              class="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
              onClick={() => switchToStep(0)}
            >
              返回创建团队
            </button>
          </div>
        )}
      </div>
    );

    // 渲染新增团队弹窗
    const renderCreateTeamDialog = () => (
      <ElDialog
        v-model={dialogVisible.value}
        title={isEditMode.value ? $t('contests.createTeamDialog.editTitle') : $t('contests.createTeamDialog.title')}
        width="500px"
        destroy-on-close
        append-to-body
        v-slots={{
          footer: () => (
            <div class="dialog-footer">
              <ElButton onClick={closeDialog}>
                {$t('contests.createTeamDialog.cancel')}
              </ElButton>
              <ElButton type="primary" onClick={handleSubmit}>
                {$t('contests.createTeamDialog.confirm')}
              </ElButton>
            </div>
          )
        }}
      >
        <ElForm
          model={formData.value}
          rules={formRules}
          label-width="100px"
          class="create-team-form"
        >
          <ElFormItem
            label="团队名称"
            prop="name"
            required
          >
            <ElInput
              v-model={formData.value.name}
              placeholder="请输入团队名称"
              maxlength={20}
              show-word-limit
            />
          </ElFormItem>

          <ElFormItem
            label="参赛组别"
            prop="groupId"
            required
          >
            <ElSelect
              v-model={formData.value.groupId}
              placeholder="请选择参赛组别"
              loading={groupLoading.value}
              style="width: 100%"
            >
              {groupOptions.value.map(option => (
                <ElOption
                  key={option.id}
                  label={option.name}
                  value={option.id}
                />
              ))}
            </ElSelect>
          </ElFormItem>

          <ElFormItem
            label="团队类型"
            prop="type"
            required
          >
            <ElSelect
              v-model={formData.value.type}
              placeholder="请选择团队类型"
              style="width: 100%"
            >
              {teamNatureOptions.map(option => (
                <ElOption
                  key={option.value}
                  label={option.label}
                  value={option.value}
                />
              ))}
            </ElSelect>
          </ElFormItem>

          <ElFormItem
            label={$t('contests.createTeamDialog.location')}
            prop="provinceCitySelection"
            required
          >
            <ElCascader
              v-model={formData.value.provinceCitySelection}
              options={provinceCityOptions as any}
              placeholder={$t('contests.createTeamDialog.locationPlaceholder')}
              clearable
              filterable
              expand-trigger="hover"
              check-strictly={false}
              emit-path={true}
              style="width: 100%"
            />
          </ElFormItem>

          <ElFormItem
            label="单位名称"
            prop="organName"
            required
          >
            <ElInput
              v-model={formData.value.organName}
              placeholder="请输入单位名称"
            />
          </ElFormItem>
        </ElForm>
      </ElDialog>
    );

    // 组件挂载时获取数据
    onMounted(async () => {
      // 并行获取组别选项和团队列表
      await Promise.all([
        fetchGroupOptions(),
        fetchTeamList()
      ]);
    });

    return () => (
      <div class="bg-[#EDEEF5] flex flex-col items-center">
        {/* 步骤条区域 */}
        {renderSteps()}

        {/* 页面标题 */}
        <div class="mb-[20px] w-[1200px]">
          <h2 class="text-2xl font-semibold text-gray-800 m-0">
            {activeStep.value === 1 ? '管理队员' : activeStep.value === 2 ? '提交报名' : activeStep.value === 3 ? '上传作品' : $t('contests.myTeam')}
          </h2>
        </div>

        <div class="w-[1200px] min-h-[616px] mb-[24px] relative">
          {/* 根据步骤显示不同内容 */}
          {activeStep.value === 3 ? (
            <UploadWorks
              onEdit-registration={handleEditRegistration}
              onResubmit-registration={handleResubmitRegistration}
            />
          ) : activeStep.value === 2 ? (
            <SubmissionForm
              editData={editRegistrationData.value}
              onSubmit-success={() => {
                editRegistrationData.value = null; // 清除编辑数据
                activeStep.value = 3; // 提交成功后进入上传作品步骤
              }}
            />
          ) : activeStep.value === 1 ? renderTeamManagement() : renderTeamList()}
        </div>

        {/* 新增团队弹窗 */}
        {renderCreateTeamDialog()}
      </div>
    );
  }
});
</script>

<style scoped>
.space-y-4>*+* {
  margin-top: 1rem;
}

.space-y-1>*+* {
  margin-top: 0.25rem;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .w-\[1200px\] {
    width: 95%;
    max-width: 1200px;
  }
}

@media (max-width: 768px) {
  .w-\[1200px\] {
    width: 95%;
    max-width: 1200px;
  }

  /* 调整步骤条在小屏幕上的布局 */
  .px-12 {
    @apply px-4;
  }

  .w-32 {
    @apply w-20;
  }

  .left-12 {
    @apply left-8;
  }
}

@media (max-width: 480px) {
  .px-12 {
    @apply px-2;
  }

  .w-32 {
    @apply w-16;
  }

  .left-12 {
    @apply left-6;
  }

  .text-sm {
    @apply text-xs;
  }
}
</style>
